package com.arunsawad.ilertu.dto;

import android.graphics.Bitmap;
import android.os.AsyncTask;

import com.arunsawad.ilertu.adapter.CategoriesAdapter;
import com.arunsawad.ilertu.common.Utils;

public class Category {
	private int id;
	private String name;
	private String imgUrl;
	private Bitmap image;
	private CategoriesAdapter adapter;

	public Category(int id, String name, String imgUrl) {
		this.id = id;
		this.name = name;
		this.imgUrl = imgUrl;
		this.image = null; // for lazy loading, can be set with a default image
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getImgUrl() {
		return imgUrl;
	}

	public void setImgUrl(String imgUrl) {
		this.imgUrl = imgUrl;
	}

	public Bitmap getImage() {
		return image;
	}

	public CategoriesAdapter getCategoriesAdapter() {
		return adapter;
	}

	public void setCategoriesAdapter(CategoriesAdapter adapter) {
		this.adapter = adapter;
	}

	public void loadImage(CategoriesAdapter adapter) {
		// hold a reference to the adapter
		this.adapter = adapter;
		if (imgUrl != null && !imgUrl.equals("")) {
			new ImageLoadTask().execute(imgUrl);
		}
	}

	private class ImageLoadTask extends AsyncTask<String, String, Bitmap> {

		@Override
		protected void onPreExecute() {
		}

		protected Bitmap doInBackground(String... param) {
			// param[0]: imgUrl
			try {
				Bitmap b = Utils.getBitmapFromURL(param[0]);
				return b;
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			}
		}

		protected void onProgressUpdate(String... progress) {
			//
		}

		protected void onPostExecute(Bitmap result) {
			if (result != null) {
				image = result;
				if (adapter != null) {
					// when image is loaded, notify the adapter
					adapter.notifyDataSetChanged();
				}
			}
		}
	}
}
